package com.study.web.action.system;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.study.common.exception.BizException;
import com.study.common.page.PageBean;
import com.study.common.utils.JsonTreeCheckBoxUtil;
import com.study.common.utils.ResponseUtil;
import com.study.common.ztree.TreeCheckBoxEntity;
import com.study.web.annotation.RequestParamNeedValidateAnnotation;
import com.study.web.context.SpringContextUtil;
import com.study.web.context.SpringMVCActionSupport;
import com.study.web.dto.MenuDto;
import com.study.web.dto.PermissionDto;
import com.study.web.entity.SysPermission;
import com.study.web.entity.SysRole;
import com.study.web.entity.SysUser;
import com.study.web.service.syspermission.SysPermissionService;
import com.study.web.service.sysrole.SysRoleService;
import com.study.web.service.sysuser.SysUserService;

import net.sf.json.JSONArray;

@Controller
@RequestMapping("/admin/system")
@SuppressWarnings("all")
/**
 * 
 * All rights Reserved, Designed By yaojinshan
 * @Title:  SystemController.java   
 * @Package com.study.web.action.system   
 * @Description: 系统模块控制器   
 * @author: yaojinshan     
 * @date:   2018年6月27日 下午3:18:27   
 * @version V1.0 
 * @Copyright: 2018 All users All rights reserved. 
 * 注意：注意：本内容仅限于学习springmvc + spring + maven + mybatis学习使用
 */
public class SystemController extends SpringMVCActionSupport {
	
	@Autowired
	private SysPermissionService sysPermissionService;
	
	@Autowired
	private SysRoleService sysRoleService;

	@Autowired
	private SysUserService sysUserService;
	private static Logger logger = LoggerFactory.getLogger(SystemController.class);
	/**
	 * @Description 查询一级菜单 <pre>
	 * @return  返回值类型: <pre>  
	 * @author 作者: yaojinshan <pre>
	 * @date 2018年6月27日 下午3:19:02 <pre> 
	 * @throws 异常: <pre>
	 */
    @RequestMapping(value = "/queryFirstLevelMenuByRoleId")
    @ResponseBody
    public String queryFirstLevelMenuByRoleId() {
        Map resultMap = new HashMap();
        String result = ResponseUtil.RES_FAIL;
        List<SysPermission> list = null;
        SysUser user = (SysUser) SecurityUtils.getSubject().getPrincipal();
        try {
        	Map<String, Object> paramsMap = new HashMap<String, Object>();
        	paramsMap.put("parentId", "0");
        	paramsMap.put("roleId",user.getRoleId());
        	list = sysPermissionService.queryFirstLevelMenuByRoleId(paramsMap);
            result = ResponseUtil.RES_SUCCESS;
        } catch (BizException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            resultMap.put("result", result);
            resultMap.put("menulist", list);
            return JSON.toJSONString(resultMap);
        }
    }
    /**
     * @Description 根据parentId查询MenuDto <pre>
     * @param parentId 父编码Id
     * @return
     * @author 作者: yaojinshan <pre>
     * @date 2018年6月27日 下午3:21:32 <pre> 
     * @throws 异常: <pre>
     */
    @RequestMapping(value = "/queryMenuByParentId")
    @ResponseBody
    public String queryMenuByParentId(String parentId) {
        Map resultMap = new HashMap();
        String result = ResponseUtil.RES_FAIL;
        List<Map<String,Object>> menuMapList = null;
        List<MenuDto> menulist = new ArrayList<MenuDto>();
        SysUser user = (SysUser) SecurityUtils.getSubject().getPrincipal();
        try {
        	Map<String,Object> paramsMap = new HashMap<String, Object>();
        	paramsMap.put("parentId", parentId);
        	paramsMap.put("roleId",user.getRoleId());
        	menuMapList = sysPermissionService.queryMenuDtoListByParentIdAndRoleId(paramsMap);
        	fillMapDataToMenuDto(menuMapList,menulist,parentId);
            result = ResponseUtil.RES_SUCCESS;
        } catch (BizException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            resultMap.put("result", result);
            resultMap.put("menulist", menulist);
            return JSON.toJSONString(resultMap);
        }
    }
    /**
     * 将map的数据 填充到dto中
     */
	private void fillMapDataToMenuDto(List<Map<String, Object>> menuMapList, List<MenuDto> menulist,String parentId) {
		for (Map<String, Object> map : menuMapList) {
			if(parentId.equals(String.valueOf(map.get("parent_id")))){
				MenuDto mto = new MenuDto();
				mto.setId((Long) map.get("id"));
				mto.setPermissionType(Integer.parseInt(String.valueOf(map.get("permission_type"))));
				mto.setUrl((String) map.get("url"));
				mto.setZhName((String) map.get("zh_name"));
				menulist.add(mto);
			}
		}
		for(MenuDto menuDto : menulist){
			List<MenuDto> childrenList = menuDto.getChildren();
			for (Map<String, Object> map : menuMapList) {
				if(String.valueOf(menuDto.getId()).equals(String.valueOf(map.get("parent_id")))){
					MenuDto mto = new MenuDto();
					mto.setId((Long) map.get("id"));
					mto.setPermissionType(Integer.parseInt(String.valueOf(map.get("permission_type"))));
					mto.setUrl((String) map.get("url"));
					mto.setZhName((String) map.get("zh_name"));
					if(null == childrenList){
						childrenList = new ArrayList<MenuDto>();
					}
					childrenList.add(mto);
					menuDto.setChildren(childrenList);
				}
			}
		}
	}
	/**
	 * @Description 查询角色管理列表数据 <pre>
	 * @param roleName 角色名称
	 * @param status 角色状态
	 * @param noPage 不分页
	 * @author 作者: yaojinshan <pre>
	 * @date 2018年6月27日 下午3:22:58 <pre> 
	 */
    @RequestMapping(value = "/queryListRolesData")
    @ResponseBody
    @RequiresPermissions("roleList:view")
    public String queryListRolesData(String roleName,String status,String noPage) {
        logger.info("roleName:" + roleName + "  pageNum:" + getPageParam().getPageNum() + " numPerPage:" + getPageParam().getNumPerPage());
        Map resultMap = new HashMap();
        String result = ResponseUtil.RES_FAIL;
        String msg = "查询角色列表数据失败";
        PageBean pageBean = null;
        try {
            Map<String, Object> paramMap = new HashMap<String, Object>();
            paramMap.put("roleName", roleName);
            paramMap.put("status", status);
            if(StringUtils.isNotEmpty(noPage)){
            	List<SysRole> roleList = sysRoleService.listBy(paramMap);
            	if(null == roleList || roleList.isEmpty()){
            		resultMap.put("roleList", new ArrayList<SysRole>());
            	}else{
            		resultMap.put("roleList", roleList);
            	}
            }else{
            	pageBean = sysRoleService.listPage(getPageParam(), paramMap);
            	if (pageBean != null && pageBean.getRecordList() != null && pageBean.getRecordList().size() > 0) {
            		resultMap.put("rows", pageBean.getRecordList());
            		resultMap.put("total", pageBean.getTotalCount());
            	} else {
            		resultMap.put("rows", new ArrayList<Object>());
            		resultMap.put("total", 0);
            	}
            }
            result = ResponseUtil.RES_SUCCESS;
            msg = "查询角色列表数据成功";
        } catch (BizException e) {
            resultMap.put("rows", new ArrayList<Object>());
            resultMap.put("total", 0);
            result = e.getCode();
            msg = e.getMessage();
            e.printStackTrace();
        } catch (Exception e) {
            resultMap.put("rows", new ArrayList<Object>());
            resultMap.put("total", 0);
            msg = e.getMessage();
            e.printStackTrace();
        } finally {
            resultMap.put("result", result);
            resultMap.put("msg", msg);
            return JSON.toJSONString(resultMap);
        }
    }
    /**
     * @Description 验证角色是否存在 <pre>
     * @param sysRole 模型驱动封装的角色对象
     * @author 作者: yaojinshan <pre>
     * @date 2018年6月27日 下午3:24:45 <pre> 
     */
    @RequestMapping("/checkRoleExist")
    @ResponseBody
    public String checkRoleExist(SysRole sysRole) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        boolean valid = true;
        try {
            Map<String, Object> paramMap = new HashMap<String, Object>();
			paramMap.put("zhName", sysRole.getZhName());
			paramMap.put("enName", sysRole.getEnName());
			List<SysRole> list = sysRoleService.listBy(paramMap);
			if(list != null && list.size() > 0){
				valid = false;
			}
        } catch (Exception e) {
        	e.printStackTrace();
        } finally {
        	resultMap.put("valid", valid);
            return JSON.toJSONString(resultMap);
        }
    }
    /**
     * @Description 新增角色 <pre>
     * @param response 响应处理类，方便AOP功能使用
     * @param sysRole 角色实体
     * @param validResult 错误信息
     * @param request 请求参数类
     * @author 作者: yaojinshan <pre>
     * @date 2018年6月27日 下午3:25:39 <pre> 
     */
    @RequestMapping(value = "addRole")
    @ResponseBody
    @RequiresPermissions("roleAdd:view")
    //@RequestParamNeedValidateAnnotation
    public String addRole(HttpServletResponse response, @Valid SysRole sysRole,HttpServletRequest request) {
    	String result = ResponseUtil.RES_FAIL;
    	String msg = "";
    	Map<String, Object> resultMap = new HashMap<String, Object>();
    	SysUser user = (SysUser) SecurityUtils.getSubject().getPrincipal();
    	try {
    		//RequestValidateUtil.checkVo(validResult);
    		sysRole.setCreaterId(user.getCreaterId());
    		sysRole.setCreateTime(new Date());
    		sysRoleService.insert(sysRole);
    		result = ResponseUtil.RES_SUCCESS;
    		msg = "新增角色成功";
    	} catch (BizException e) {
    		msg = e.getMessage();
    		e.printStackTrace();
    	} catch (Exception e) {
    		msg = "新增角色系统异常，请查找原因！";
    		e.printStackTrace();
    	} finally {
    		resultMap.put("msg", msg);
    		resultMap.put("result", result);
    		return JSON.toJSONString(resultMap);
    	}
    }
    /**
     * @Description 通过Id查询角色 <pre>
     * @param roleId 角色Id
     * @author 作者: yaojinshan <pre>
     * @date 2018年6月27日 下午3:28:28 <pre> 
     */
    @RequestMapping(value = "queryRoleById")
    @ResponseBody
    @RequiresPermissions("roleUpdate:view")
    public String queryRoleById(@RequestParam(value="roleId", required = true)Long roleId) {
    	String result = ResponseUtil.RES_FAIL;
    	String msg = "查询角色失败：";
    	Map<String, Object> resultMap = new HashMap<String, Object>();
    	SysRole sysRole = null;
    	try {
    		sysRole = sysRoleService.getById(roleId);
    		resultMap.put("sysRole", sysRole);
    		result = ResponseUtil.RES_SUCCESS;
    		msg = "查询角色成功！";
    	} catch (BizException e) {
    		msg = e.getMessage();
    		e.printStackTrace();
    	} catch (Exception e) {
    		msg = "查询角色系统异常，请查找原因！";
    		e.printStackTrace();
    	} finally {
    		resultMap.put("msg", msg);
    		resultMap.put("result", result);
    		return JSON.toJSONString(resultMap);
    	}
    }
    /**
     * @Description 更新角色 <pre>
     * @param response
     * @param sysRole
     * @param validResult
     * @param request
     * @author 作者: yaojinshan <pre>
     * @date 2018年6月27日 下午3:29:40 <pre> 
     */
    @RequestMapping(value = "updateRole")
    @ResponseBody
    @RequiresPermissions("roleUpdate:view")
    //@RequestParamNeedValidateAnnotation
    public String updateRole(HttpServletResponse response,@Valid SysRole sysRole,HttpServletRequest request) {
    	String result = ResponseUtil.RES_FAIL;
    	String msg = "";
    	Map<String, Object> resultMap = new HashMap<String, Object>();
    	SysUser user = (SysUser) SecurityUtils.getSubject().getPrincipal();
    	try {
    		sysRole.setUpdaterId(user.getCreaterId());
    		sysRole.setUpdateTime(new Date());
    		sysRoleService.update(sysRole);
    		result = ResponseUtil.RES_SUCCESS;
    		msg = "修改角色成功";
    	} catch (BizException e) {
    		msg = e.getMessage();
    		e.printStackTrace();
    	} catch (Exception e) {
    		msg = "修改角色系统异常，请查找原因！";
    		e.printStackTrace();
    	} finally {
    		resultMap.put("msg", msg);
    		resultMap.put("result", result);
    		return JSON.toJSONString(resultMap);
    	}
    }
    /**
     * @Description 删除角色 <pre>
     * @param ids 角色id数组
     * @author 作者: yaojinshan <pre>
     * @date 2018年6月27日 下午3:30:03 <pre> 
     */
    @RequestMapping(value = "batchDeleteRole")
    @ResponseBody
    @RequiresPermissions("roleDelete:action")
    public String batchDeleteRole(@RequestParam(value="ids[]", required = true) List<Long> ids) {
    	String result = ResponseUtil.RES_FAIL;
    	String msg = "";
    	Map<String, Object> resultMap = new HashMap<String, Object>();
    	try {
    		if(ids == null || ids.size() == 0){
    			throw BizException.PARAM_NULL_ERROR;
    		}
    		for(Long id : ids){
    			if(id == SpringContextUtil.getSuperAdministratorRoleId()){
    				throw new BizException("超级管理员角色不允许删除！");
    			}
    		}
    		sysRoleService.batchDeleteRole(ids);
    		result = ResponseUtil.RES_SUCCESS;
    		msg = "删除角色成功";
    	} catch (BizException e) {
    		msg = e.getMessage();
    		e.printStackTrace();
    	} catch (Exception e) {
    		msg = "删除角色系统异常，请查找原因！";
    		e.printStackTrace();
    	} finally {
    		resultMap.put("msg", msg);
    		resultMap.put("result", result);
    		return JSON.toJSONString(resultMap);
    	}
    }
    /**
     * @Description  查询角色的具体权限 <pre>
     * @param roleId 角色Id
     * @author 作者: yaojinshan <pre>
     * @date 2018年6月27日 下午3:30:38 <pre> 
     */
    @RequestMapping(value = "/queryRolePermission")
    @ResponseBody
    @RequiresPermissions("updateRolePermission:view")
    public JSONArray queryRolePermission(@RequestParam(value="roleId", required = true)Long roleId) {
    	Map<String, Object> resultMap = new HashMap<String, Object>();
        List<PermissionDto> allUseableRolePermissson = null;//角色所有可用的权限
        String jsonTreeData = "";
        List<Object> treeList = new ArrayList<Object>() ;
        try {
            Map<String, Object> allUseableRolePermisssonParamMap = new HashMap<String, Object>();
            allUseableRolePermisssonParamMap.put("status", 1);
            allUseableRolePermisssonParamMap.put("roleId", roleId);
            allUseableRolePermissson = sysPermissionService.queryPermisssonOfRole(allUseableRolePermisssonParamMap);
            for (PermissionDto permissionDto : allUseableRolePermissson) {
            	String check = "";
            	TreeCheckBoxEntity tcbe = null;
            	check = (0 == permissionDto.getHashPermission()) ? "" : "true";
            	if(0l == permissionDto.getParentId()){
            		tcbe =  new TreeCheckBoxEntity(String.valueOf(permissionDto.getRightsId()),permissionDto.getZhName(),
                			"",check);
            	}else{
            		tcbe = new TreeCheckBoxEntity(String.valueOf(permissionDto.getRightsId()),permissionDto.getZhName(),
            				String.valueOf(permissionDto.getParentId()),check);
            	}
            	treeList.add(tcbe);
			}
            jsonTreeData = JsonTreeCheckBoxUtil.getTreeJsonStrNormal(new String[]{"id","name","pro","checked"}, treeList);
        } catch (BizException e) {
            logger.error("编辑或查看某角色的权限异常", e);
            e.printStackTrace();
        } catch (Exception e) {
            logger.error("编辑或查看制定角色的权限异常", e);
            e.printStackTrace();
        } finally {
        	return JSONArray.fromObject(jsonTreeData);
        }
    }
    
    /**
     * @Description 更新角色权限 <pre>
     * @param ids 权限字符串
     * @param roleId 角色Id  
     * @author 作者: yaojinshan <pre>
     * @date 2018年6月27日 下午3:31:10 <pre> 
     */
    @RequestMapping(value = "updateRolePermission")
    @ResponseBody
    @RequiresPermissions("updateRolePermission:view")
    public String updateRolePermission(@RequestParam(value="ids[]", required = true)List<Long> ids,Long roleId) {
    	String result = ResponseUtil.RES_FAIL;
    	String msg = "";
    	Map<String, Object> resultMap = new HashMap<String, Object>();
    	SysUser user = (SysUser) SecurityUtils.getSubject().getPrincipal();
    	try {
    		if(roleId == null || roleId == 0l){
    			throw BizException.PARAM_NULL_ERROR;
    		}
//    		if(SpringContextUtil.getSuperAdministratorLoginName().equals(user.getLoginName()) && SpringContextUtil.getSuperAdministratorRoleId() == roleId){
//    			msg = "超过管理员用户持有所有的权限，不能修改!";
//    		}else{
    			//1.删除角色之前所有的权限,保存现有的权限
    			sysPermissionService.deleteOldRolePermissionAndBatchInsert(ids,roleId);
    			result = ResponseUtil.RES_SUCCESS;
    			msg = "修改角色权限成功";
//    		}
    	} catch (BizException e) {
    		msg = e.getMessage();
    		e.printStackTrace();
    	} catch (Exception e) {
    		msg = "修改角色权限系统异常，请查找原因！";
    		e.printStackTrace();
    	} finally {
    		resultMap.put("msg", msg);
    		resultMap.put("result", result);
    		return JSON.toJSONString(resultMap);
    	}
    }
    /**
     * @Description 权限列表数据 <pre>
     * @param zhName 权限名称
     * @param status 权限状态
     * @param parentId 父编码
     * @author 作者: yaojinshan <pre>
     * @date 2018年6月27日 下午3:31:46 <pre> 
     */
    @RequestMapping(value = "/queryListPermissionData")
    @ResponseBody
    @RequiresPermissions("permissionList:view")
    public String queryListPermissionData(String zhName,String status,String parentId) {
        logger.info("zhName:" + zhName + "  pageNum:" + getPageParam().getPageNum() + " numPerPage:" + getPageParam().getNumPerPage());
        Map resultMap = new HashMap();
        String result = ResponseUtil.RES_FAIL;
        String msg = "查询权限列表数据失败";
        PageBean pageBean = null;
        try {
            Map<String, Object> paramMap = new HashMap<String, Object>();
            paramMap.put("zhName", zhName);
            paramMap.put("status", status);
            if(StringUtils.isEmpty(parentId)){
            	paramMap.put("parentId", "0");
            }else{
            	paramMap.put("parentId", parentId);
            }
			pageBean = sysPermissionService.listPage(getPageParam(), paramMap);
            if (pageBean != null && pageBean.getRecordList() != null && pageBean.getRecordList().size() > 0) {
                resultMap.put("rows", pageBean.getRecordList());
                resultMap.put("total", pageBean.getTotalCount());
                result = ResponseUtil.RES_SUCCESS;
            } else {
                resultMap.put("rows", new ArrayList<Object>());
                resultMap.put("total", 0);
            }
            msg = "查询权限列表数据成功";
        } catch (BizException e) {
            resultMap.put("rows", new ArrayList<Object>());
            resultMap.put("total", 0);
            result = e.getCode();
            msg = e.getMessage();
            e.printStackTrace();
        } catch (Exception e) {
            resultMap.put("rows", new ArrayList<Object>());
            resultMap.put("total", 0);
            msg = e.getMessage();
            e.printStackTrace();
        } finally {
            resultMap.put("result", result);
            resultMap.put("msg", msg);
            return JSON.toJSONString(resultMap);
        }
    }
    /**
     * @Description 验证权限是否存在 <pre>
     * @param sysPermission
     * @author 作者: yaojinshan <pre>
     * @date 2018年6月27日 下午3:32:29 <pre> 
     */
    @RequestMapping("/checkPermissionExist")
    @ResponseBody
    public String checkPermissionExist(SysPermission sysPermission) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        boolean valid = true;
        try {
            Map<String, Object> paramMap = new HashMap<String, Object>();
			paramMap.put("zhName", sysPermission.getZhName());
			paramMap.put("zhNameStrongMatch", "1");
			paramMap.put("zhName", sysPermission.getZhName());
			paramMap.put("enNameStrongMatch", "1");
			List<SysPermission> list = sysPermissionService.listBy(paramMap);
			if(list != null && list.size() > 0){
				valid = false;
			}
        } catch (Exception e) {
        	e.printStackTrace();
        } finally {
        	resultMap.put("valid", valid);
            return JSON.toJSONString(resultMap);
        }
    }
    /**
     * @Description 新增权限 <pre>
     * @param response
     * @param sysPermission
     * @param validResult
     * @param request
     * @author 作者: yaojinshan <pre>
     * @date 2018年6月27日 下午3:32:45 <pre> 
     */
    @RequestMapping(value = "addPermission")
    @ResponseBody
    @RequiresPermissions("permissionAdd:view")
    //@RequestParamNeedValidateAnnotation
    public String addPermission(HttpServletResponse response, @Valid SysPermission sysPermission,HttpServletRequest request) {
    	String result = ResponseUtil.RES_FAIL;
    	String msg = "";
    	Map<String, Object> resultMap = new HashMap<String, Object>();
    	SysUser user = (SysUser) SecurityUtils.getSubject().getPrincipal();
    	try {
    		sysPermission.setCreaterId(user.getCreaterId());
    		sysPermission.setCreateTime(new Date());
    		sysPermissionService.insert(sysPermission);
    		result = ResponseUtil.RES_SUCCESS;
    		msg = "新增权限成功！";
    	} catch (BizException e) {
    		msg = e.getMessage();
    		e.printStackTrace();
    	} catch (Exception e) {
    		msg = "新增权限系统异常，请查找原因！";
    		e.printStackTrace();
    	} finally {
    		resultMap.put("msg", msg);
    		resultMap.put("result", result);
    		return JSON.toJSONString(resultMap);
    	}
    }
    /**
     * @Description 通过Id查询权限 <pre>
     * @param permissionId 权限Id
     * @author 作者: yaojinshan <pre>
     * @date 2018年6月27日 下午3:33:11 <pre> 
     */
    @RequestMapping(value = "queryPermissionById")
    @ResponseBody
    @RequiresPermissions("permissionUpdate:view")
    public String queryPermissionById(@RequestParam(value="permissionId", required = true)Long permissionId) {
    	String result = ResponseUtil.RES_FAIL;
    	String msg = "查询权限失败：";
    	Map<String, Object> resultMap = new HashMap<String, Object>();
    	SysPermission sysPermission = null;
    	try {
    		if(permissionId == null){
    			throw BizException.PARAM_NULL_ERROR;
    		}
    		sysPermission = sysPermissionService.getById(permissionId);
    		resultMap.put("sysPermission", sysPermission);
    		result = ResponseUtil.RES_SUCCESS;
    		msg = "查询权限成功！";
    	} catch (BizException e) {
    		msg = e.getMessage();
    		e.printStackTrace();
    	} catch (Exception e) {
    		msg = "查询权限系统异常，请查找原因！";
    		e.printStackTrace();
    	} finally {
    		resultMap.put("msg", msg);
    		resultMap.put("result", result);
    		return JSON.toJSONString(resultMap);
    	}
    }
    /**
     * @Description 修改权限 <pre>
     * @param response
     * @param sysPermission
     * @param validResult
     * @param request
     * @author 作者: yaojinshan <pre>
     * @date 2018年6月27日 下午3:33:36 <pre> 
     */
    @RequestMapping(value = "updatePermission")
    @ResponseBody
    @RequiresPermissions("permissionUpdate:view")
    //@RequestParamNeedValidateAnnotation
    public String updatePermission(HttpServletResponse response, @Valid SysPermission sysPermission,HttpServletRequest request) {
    	String result = ResponseUtil.RES_FAIL;
    	String msg = "";
    	Map<String, Object> resultMap = new HashMap<String, Object>();
    	SysUser user = (SysUser) SecurityUtils.getSubject().getPrincipal();
    	try {
    		sysPermission.setCreaterId(user.getCreaterId());
    		sysPermission.setCreateTime(new Date());
    		sysPermissionService.update(sysPermission);
    		result = ResponseUtil.RES_SUCCESS;
    		msg = "修改权限成功！";
    	} catch (BizException e) {
    		msg = e.getMessage();
    		e.printStackTrace();
    	} catch (Exception e) {
    		msg = "修改权限系统异常，请查找原因！";
    		e.printStackTrace();
    	} finally {
    		resultMap.put("msg", msg);
    		resultMap.put("result", result);
    		return JSON.toJSONString(resultMap);
    	}
    }
	/**
	 * @Description 查询管理员列表数据 <pre>
	 * @param loginName 登录名
	 * @param status 用户状态
	 * @author 作者: yaojinshan <pre>
	 * @date 2018年6月27日 下午3:22:58 <pre> 
	 */
    @RequestMapping(value = "/queryListUserData")
    @ResponseBody
    @RequiresPermissions("userList:view")
    public String queryListUserData(String loginName,String status,String isDelete) {
        logger.info("loginName:" + loginName + "  pageNum:" + getPageParam().getPageNum() + " numPerPage:" + getPageParam().getNumPerPage());
        Map resultMap = new HashMap();
        String result = ResponseUtil.RES_FAIL;
        String msg = "查询用户列表数据失败";
        PageBean pageBean = null;
        try {
            Map<String, Object> paramMap = new HashMap<String, Object>();
            paramMap.put("loginName", loginName);
            paramMap.put("status", status);
            paramMap.put("isDelete", isDelete);
			pageBean = sysUserService.listPage(getPageParam(), paramMap);
            if (pageBean != null && pageBean.getRecordList() != null && pageBean.getRecordList().size() > 0) {
                resultMap.put("rows", pageBean.getRecordList());
                resultMap.put("total", pageBean.getTotalCount());
                result = ResponseUtil.RES_SUCCESS;
            } else {
                resultMap.put("rows", new ArrayList<Object>());
                resultMap.put("total", 0);
            }
            msg = "查询用户列表数据成功";
        } catch (BizException e) {
            resultMap.put("rows", new ArrayList<Object>());
            resultMap.put("total", 0);
            result = e.getCode();
            msg = e.getMessage();
            e.printStackTrace();
        } catch (Exception e) {
            resultMap.put("rows", new ArrayList<Object>());
            resultMap.put("total", 0);
            msg = e.getMessage();
            e.printStackTrace();
        } finally {
            resultMap.put("result", result);
            resultMap.put("msg", msg);
            return JSON.toJSONString(resultMap);
        }
    }
    /**
     * @Description 更新用户状态 <pre>
     * @param updateType 操作类型 freeze:冻结 ，unfreeze：解冻，delete：删除用户
     * @param ids[] 管理员Id数组
     * @author 作者: yaojinshan <pre>
     * @date 2018年6月29日 上午10:44:33 <pre> 
     */
    @RequestMapping(value = "updateSysUserStatus")
    @ResponseBody
    @RequiresRoles("admin")
    public String updateSysUserStatus(@RequestParam(value="updateType", required = true)String updateType,@RequestParam(value="ids[]", required = true)List<Long> ids) {
    	String result = ResponseUtil.RES_FAIL;
    	String msg = "更新用户状态失败";
    	Map<String, Object> resultMap = new HashMap<String, Object>();
    	SysUser user = (SysUser) SecurityUtils.getSubject().getPrincipal();
    	try {
    		for (long id : ids) {
				if(SpringContextUtil.getSuperAdministratorUserId() == id){
					throw new BizException("超级管理员用户不允许删除或者冻结！");
				}
			}
    		Map<String,Object> paramMap = new HashMap<String, Object>();
    		if("freeze".equals(updateType) || "unfreeze".equals(updateType)){
    			if("freeze".equals(updateType)){
    				paramMap.put("status", "2");
    			}else{
    				paramMap.put("status", "1");
    			}
    			paramMap.put("ids", ids);
    		}else if("delete".equals(updateType)){
    			paramMap.put("isDelete", "1");
    		}
    		paramMap.put("updaterId", user.getId());
    		paramMap.put("updateTime",new Date());
    		long updateResult = sysUserService.batchUpdateSysUserStatus(paramMap);
    		if(updateResult > 0){
    			result = ResponseUtil.RES_SUCCESS;
    			msg = "更新用户状态成功";
    		}else{
    			msg = "更新用户状态出现异常！";
    		}
    	} catch (BizException e) {
    		msg = e.getMessage();
    		e.printStackTrace();
    	} catch (Exception e) {
    		msg = "更新用户状态系统异常，请查找原因！";
    		e.printStackTrace();
    	} finally {
    		resultMap.put("msg", msg);
    		resultMap.put("result", result);
    		return JSON.toJSONString(resultMap);
    	}
    }
    /**
     * @Description 新增管理员 <pre>
     * @param response
     * @param sysUser 管理员
     * @param validResult
     * @param request
     * @author 作者: yaojinshan <pre>
     * @date 2018年6月27日 下午3:29:40 <pre> 
     */
    @RequestMapping(value = "addUser")
    @ResponseBody
    @RequiresPermissions("userAdd:view")
    //@RequestParamNeedValidateAnnotation
    public String addUser(HttpServletResponse response,@Valid SysUser sysUser,HttpServletRequest request) {
    	String result = ResponseUtil.RES_FAIL;
    	String msg = "";
    	Map<String, Object> resultMap = new HashMap<String, Object>();
    	SysUser user = (SysUser) SecurityUtils.getSubject().getPrincipal();
    	try {
    		sysUser.setCreaterId(user.getCreaterId());
    		sysUser.setCreateTime(new Date());
    		sysUser.setPassword(DigestUtils.md5Hex(sysUser.getPassword()));
    		sysUserService.insert(sysUser);
    		result = ResponseUtil.RES_SUCCESS;
    		msg = "新增管理员成功";
    	} catch (BizException e) {
    		msg = e.getMessage();
    		e.printStackTrace();
    	} catch (Exception e) {
    		msg = "新增管理员系统异常，请查找原因！";
    		e.printStackTrace();
    	} finally {
    		resultMap.put("msg", msg);
    		resultMap.put("result", result);
    		return JSON.toJSONString(resultMap);
    	}
    }
    /**
     * @Description 通过Id查询管理员 <pre>
     * @param userId
     * @author 作者: yaojinshan <pre>
     * @date 2018年6月29日 下午3:28:28 <pre> 
     */
    @RequestMapping(value = "queryUserById")
    @ResponseBody
    @RequiresPermissions("userUpdate:view")
    public String queryUserById(@RequestParam(value="userId", required = true)Long userId) {
    	String result = ResponseUtil.RES_FAIL;
    	String msg = "查询管理员失败：";
    	Map<String, Object> resultMap = new HashMap<String, Object>();
    	SysUser sysUser = null;
    	try {
    		sysUser = sysUserService.getById(userId);
    		resultMap.put("sysUser", sysUser);
    		result = ResponseUtil.RES_SUCCESS;
    		msg = "查询管理员成功！";
    	} catch (BizException e) {
    		msg = e.getMessage();
    		e.printStackTrace();
    	} catch (Exception e) {
    		msg = "查询管理员系统异常，请查找原因！";
    		e.printStackTrace();
    	} finally {
    		resultMap.put("msg", msg);
    		resultMap.put("result", result);
    		return JSON.toJSONString(resultMap);
    	}
    }
    /**
     * @Description 修改管理员 <pre>
     * @param response
     * @param sysUser
     * @param validResult
     * @param request
     * @author 作者: yaojinshan <pre>
     * @date 2018年6月29日 下午3:43:36 <pre> 
     */
    @RequestMapping(value = "updateUser")
    @ResponseBody
    @RequiresPermissions("userUpdate:view")
    //@RequestParamNeedValidateAnnotation
    public String updateUser(HttpServletResponse response, @Valid SysUser sysUser,HttpServletRequest request) {
    	String result = ResponseUtil.RES_FAIL;
    	String msg = "";
    	Map<String, Object> resultMap = new HashMap<String, Object>();
    	SysUser user = (SysUser) SecurityUtils.getSubject().getPrincipal();
    	try {
    		if(sysUser.getLoginName() == SpringContextUtil.getSuperAdministratorLoginName()){
    			throw new BizException("非法修改超级管理员请求！");
    		}
    		sysUser.setPassword("");
    		sysUser.setUpdaterId(user.getCreaterId());
    		sysUser.setUpdateTime(new Date());
    		sysUserService.update(sysUser);
    		result = ResponseUtil.RES_SUCCESS;
    		msg = "修改管理员成功！";
    	} catch (BizException e) {
    		msg = e.getMessage();
    		e.printStackTrace();
    	} catch (Exception e) {
    		msg = "修改管理员系统异常，请查找原因！";
    		e.printStackTrace();
    	} finally {
    		resultMap.put("msg", msg);
    		resultMap.put("result", result);
    		return JSON.toJSONString(resultMap);
    	}
    }
    /**
     * @Description 修改管理员密码<pre>
     * @param response
     * @param sysUser
     * @param validResult
     * @param request
     * @author 作者: yaojinshan <pre>
     * @date 2018年6月29日 下午3:43:36 <pre> 
     */
    @RequestMapping(value = "updateUserPassword")
    @ResponseBody
    @RequiresPermissions("userPasswordUpdate:view")
    public String updateUserPassword(@RequestParam(value="userId", required = true)Long userId,@RequestParam(value="loginName", required = true)String loginName,
    		@RequestParam(value="password", required = true)String password) {
    	String result = ResponseUtil.RES_FAIL;
    	String msg = "修改管理员密码失败";
    	Map<String, Object> resultMap = new HashMap<String, Object>();
    	SysUser loginUser = (SysUser) SecurityUtils.getSubject().getPrincipal();
    	try {
    		SysUser sysUser = sysUserService.getById(userId);
    		if(sysUser == null ){
    			throw new BizException("被修改的用户不存在");
    		}
    		if(!sysUser.getLoginName().equals(loginName)){
    			throw new BizException("非法请求,登录名被篡改！");
    		}
    		sysUser.setPassword(DigestUtils.md5Hex(sysUser.getPassword()));
    		sysUser.setUpdaterId(loginUser.getCreaterId());
    		sysUser.setUpdateTime(new Date());
    		sysUserService.update(sysUser);
    		result = ResponseUtil.RES_SUCCESS;
    		msg = "修改管理员密码成功！";
    	} catch (BizException e) {
    		msg = e.getMessage();
    		e.printStackTrace();
    	} catch (Exception e) {
    		msg = "修改管理员密码系统异常，请查找原因！";
    		e.printStackTrace();
    	} finally {
    		resultMap.put("msg", msg);
    		resultMap.put("result", result);
    		return JSON.toJSONString(resultMap);
    	}
    }
}
